import { ECurveParamsType, IntermediateCurveParam } from '@/types';
import { getArc2Angle, vector22Object } from '@/utils';
// @ts-ignore
import { Intersection, Shapes } from 'kld-intersections';

function getShape(intermediateCurveParam: IntermediateCurveParam) {
  const { startPoint, endPoint } = intermediateCurveParam;
  if (intermediateCurveParam.type === ECurveParamsType.Line) {
    const x1 = startPoint.x;
    const y1 = startPoint.y;
    const x2 = endPoint.x;
    const y2 = endPoint.y;
    return Shapes.line(x1, y1, x2, y2);
  } else {
    const { circle } = intermediateCurveParam;
    const centerX = circle.center.x;
    const centerY = circle.center.y;
    const radiusX = circle.radius;
    const radiusY = radiusX;
    const [startRadians, endRadians] = getArc2Angle(
      circle.center,
      startPoint,
      endPoint,
    );
    return Shapes.arc(
      centerX,
      centerY,
      radiusX,
      radiusY,
      startRadians,
      endRadians,
    );
  }
}

export function getIntersectionOfCurves([
  intermediateCurveParam1,
  intermediateCurveParam2,
]: [IntermediateCurveParam, IntermediateCurveParam]) {
  const point = Intersection.intersect(
    getShape(intermediateCurveParam1),
    getShape(intermediateCurveParam2),
  ).points[0];
  if (!point) return;
  return vector22Object(point);
}
